<?php
/**
 * Created by PhpStorm.
 * User: Guangpeng Chen
 * Date: 15-1-20
 * Time: 下午3:52
 */
include("/var/www/html/alipay/lib/alipay_notify.class.php");
include '/var/www/html/new/com.inc.php';
include("/var/www/html/new/d/class/SoapInit.class.php");
define('ACTION_MONEY_ADD',0);
define('ACTION_MONEY_CUT',1);
function write_logs($txt,$file='/var/www/html/new/d/module/alipay_refund/log.txt'){
    echo $txt . '<br/>';
    return false;
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

$json = <<<JSON
{
"sign":"5968223849bf6257805fbb4f24996931",
"result_details":"2015041400001000700051024275^0.03^SUCCESS",
"notify_time":"2015-04-13 10:56:39",
"sign_type":"MD5",
"notify_type":"batch_refund_notify",
"notify_id":"5ba7882ffe5ec81e2348014314437abgxc",
"batch_no":"2015041414475270",
"success_num":"1"
}
JSON;
$array = json_decode($json, true);
//计算得出通知验证结果
$verify_result = true;
if($verify_result) {//验证成功
    //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
    //批次号
    $batch_no = $array['batch_no'];
    //批量退款数据中转账成功的笔数
    $success_num = $array['success_num'];
    //批量退款数据中的详细信息
    $result_details_arr = explode('#', $array['result_details']);

    foreach ($result_details_arr as $result_details) {
        $result_detail  = explode('^',$result_details);
        $trade_no       = $result_detail[0];//交易号
        $total_fee      = $result_detail[1] * 100;
        //退款结果验证，之前没有加这个判断导致重复扣钱了。RESULT_AMOUNT_NOT_VALID，SUCCESS
        if (strpos($result_detail[2], 'SUCCESS') === false) {
            write_logs("失败:{$result_details}", LOG_NAME);
            continue;
        }
        $sql = "SELECT out_trade_no AS ordernum FROM pft_alipay_rec WHERE trade_no='$trade_no' LIMIT 1";
//        echo $sql;
        //exit;
//        write_logs("sql1:" . $sql);
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $ordernum = $GLOBALS['le']->f('ordernum');
//        echo $ordernum;
//        exit;
        //TODO::根据交易号获取订单数据
        $sql = "SELECT id,aid,refund_status FROM pft_order_refund"
            ." WHERE batch_no='$batch_no' AND ordernum='$ordernum' LIMIT 1";
        write_logs("sql2:" . $sql);
        $GLOBALS['le']->query($sql);
        $refund_data = $GLOBALS['le']->fetch_assoc();
        if ($refund_data) {
            $tnum        = $refund_data['refund_num'];
            if ($refund_data['status']==1) {
                write_logs("记录已更新不需要重复更新.订单号[{$ordernum}]批次号[{$batch_no}]");
                //如果这个退款已经处理，不往下执行
                continue;
            }
            write_logs("退款成功.订单号[{$ordernum}]批次号[{$batch_no}]", LOG_NAME);
            $sql = "UPDATE pft_order_refund SET refund_status=1,handler_time=now()"
                ." WHERE batch_no='$batch_no' AND ordernum='$ordernum'";
//            write_logs("sql3:" . $sql);
            $GLOBALS['le']->query($sql);
            //TODO::上级供应商扣钱
            $soap = new SoapClient(null,array(
                    "location" => "http://localhost/open/openService/pft_insideMX.php",
                    "uri" => "www.16u.com?ac_16u=16ucom|pw_16u=c33367701511b4f6020ec61ded352059|auth_16u=true")
            );
            $xml  = $soap->Order_Globle_Search("", "", "", "", "", "", "", "", "", "", "", "",
                $ordernum, "", "", "", "", "", "", "1", "0", "1", "0", "0",
                "", "0", "", "0", "", "", "", "0", "0");
//            echo $xml;
            $order_arr = simplexml_load_string($xml);
//print_r($order_arr);Response;
            if (!count($order_arr)) {
                write_logs("[{$ordernum}]|订单号不能为空",LOG_NAME);
            }
            //TODO::上级扣钱
            $mid_not_cut = array(7517,7133,7134,7135,7136,);//鼓浪屿，云顶的供应商ID
            $aid         = (int)$order_arr->Rec->UUaid;
//            echo $aid;
//            exit;
            if ( !in_array( $aid, $mid_not_cut )) {
                $res = $soap->PFT_Member_Fund_Modify($aid, 0, $total_fee,
                    ACTION_MONEY_CUT, 0, null, 0, 1,$ordernum);
                write_logs("{$ordernum}|上级供应商扣钱($aid)：{$res},$total_fee",LOG_NAME);
            }

            $sql = "UPDATE pft_alipay_rec SET status=2 WHERE trade_no='$trade_no' LIMIT 1";
//            write_logs("sql4:" . $sql);
            $GLOBALS['le']->query($sql);
            //添加交易记录

            //交易记录
//            $str="INSERT INTO pft_member_alipay SET fid={$refund_data['aid']},"
//                ."total_fee=$total_fee,orderid='$ordernum',money=$total_fee,"
//                ."daction=1,dtype=1,rectime=now(),ali_account=''";
//            write_logs("sql5 没有执行:" . $str, LOG_NAME);
//            $GLOBALS['le']->query($str);
            //$GLOBALS['le']->query($str);
        } else {
            write_logs("记录不存在.订单号[{$ordernum}]批次号[{$batch_no}]", LOG_NAME);
        }
    }
    echo "success";     //请不要修改或删除
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
else {
    //验证失败
    echo "fail";
    define('LOG_NAME_FAIL', '/var/www/html/new/d/module/alipay_refund/log_fail_' . date('Ymd').'.txt');
    write_logs("验证失败", LOG_NAME_FAIL);

    //将订单状态改成退款前
    //调试用，写文本函数记录程序运行情况是否正常
    //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
}